import 'dart:async';
import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:sui_shou_pai/Utils/aes_util.dart';
import 'package:sui_shou_pai/Utils/storage_util.dart';
import 'package:sui_shou_pai/login/login.dart';
import 'package:sui_shou_pai/my/init_info/init_information.dart';
import 'package:sui_shou_pai/network/http_config.dart';
import 'package:sui_shou_pai/network/http_request.dart';

class UpdatePassword extends StatefulWidget {
  @override
  _UpdatePasswordState createState() => _UpdatePasswordState();
}

class _UpdatePasswordState extends State<UpdatePassword> {
  bool isButtonEnable = true; //按钮状态  是否可点击
  String buttonText = '发送验证码'; //初始文本
  String phone =
      "${InitInformation.phone.substring(0, 3)}****${InitInformation.phone.substring(7, 11)}";
  int count = 60; //初始倒计时时间
  Timer timer; //倒计时的计时器
  TextEditingController mController = TextEditingController();
  TextEditingController oriPasswordController = TextEditingController();
  TextEditingController newPasswordController = TextEditingController();
  TextEditingController repeatPasswordController = TextEditingController();

  bool newPasswordVisible;
  bool repeatPasswordVisible;
  bool oriPasswordVisible;

  void _buttonClickListen() {
    setState(() {
      if (isButtonEnable) {
        //当按钮可点击时
        isButtonEnable = false; //按钮状态标记
        _initTimer();

        return null; //返回null按钮禁止点击
      } else {
        //当按钮不可点击时
//        debugPrint('false');
        return null; //返回null按钮禁止点击
      }
    });
  }

  void _initTimer() {
    timer = new Timer.periodic(Duration(seconds: 1), (Timer timer) {
      count--;
      setState(() {
        if (count == 0) {
          timer.cancel(); //倒计时结束取消定时器
          isButtonEnable = true; //按钮可点击
          count = 60; //重置时间
          buttonText = '发送验证码'; //重置按钮文本
        } else {
          buttonText = '重新发送($count)'; //更新文本内容
        }
      });
    });
  }

  @override
  void initState() {
    super.initState();
    newPasswordVisible = true;
    repeatPasswordVisible = true;
    oriPasswordVisible = true;
  }

  @override
  void dispose() {
    timer?.cancel(); //销毁计时器
    timer = null;
    mController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("修改密码"),
      ),
      body: Material(
        child: SingleChildScrollView(
          child: Container(
            child: Column(
//        mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                _buildPhoneWidget(),
                _buildVerifyCodeWidget(),
                _buildOriPasswordWidget(),
                _buildNewPasswordWidget(),
                _buildRepeatPasswordWidget(),
                Container(
                  width: double.infinity,
                  height: 45,
                  margin: EdgeInsets.only(top: 50, left: 10, right: 10),
                  child: ElevatedButton(
                    onPressed: () {
                      updatePassword();
                    },
                    child: Text(
                      '确认',
                      style: TextStyle(color: Colors.white, fontSize: 15),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildPhoneWidget() {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(left: 10, right: 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                  crossAxisAlignment: CrossAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.baseline,
        textBaseline: TextBaseline.ideographic,
        children: <Widget>[
          Container(
            width: 60,
            child: Text(
              '手机号',
              style: TextStyle(fontSize: 15, color: Color(0xff333333)),
            ),
          ),
          Expanded(
            child: Padding(
              padding: EdgeInsets.only(left: 20, right: 15, top: 15),
              child: TextFormField(
                keyboardType: TextInputType.number,
                maxLines: 1,
                onSaved: (value) {},
                // controller: mController,
                textAlign: TextAlign.left,
                enabled: false,
                inputFormatters: [LengthLimitingTextInputFormatter(6)],
                decoration: InputDecoration(
                  hintText: (phone),
                  contentPadding: EdgeInsets.only(top: -5, bottom: 0),
                  hintStyle: TextStyle(
                    color: Color(0xff999999),
                    fontSize: 15,
                  ),
                  alignLabelWithHint: true,
                  border: OutlineInputBorder(borderSide: BorderSide.none),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildVerifyCodeWidget() {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(left: 10, right: 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                  crossAxisAlignment: CrossAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.baseline,
        textBaseline: TextBaseline.ideographic,
        children: <Widget>[
          Container(
            width: 60,
            child: Text(
              '验证码',
              style: TextStyle(fontSize: 15, color: Color(0xff333333)),
            ),
          ),
          Expanded(
            child: Padding(
              padding: EdgeInsets.only(left: 20, right: 15, top: 15),
              child: TextFormField(
                keyboardType: TextInputType.number,
                maxLines: 1,
                onSaved: (value) {},
                controller: mController,
                textAlign: TextAlign.left,
                inputFormatters: [LengthLimitingTextInputFormatter(6)],
                decoration: InputDecoration(
                  hintText: ('填写验证码'),
                  contentPadding: EdgeInsets.only(top: -5, bottom: 0),
                  hintStyle: TextStyle(
                    color: Color(0xff999999),
                    fontSize: 15,
                  ),
                  alignLabelWithHint: true,
                  border: OutlineInputBorder(borderSide: BorderSide.none),
                ),
              ),
            ),
          ),
          Container(
            width: 120,
            child: FlatButton(
              disabledColor: Colors.grey.withOpacity(0.1),
              //按钮禁用时的颜色
              disabledTextColor: Colors.white,
              //按钮禁用时的文本颜色
              textColor:
                  isButtonEnable ? Colors.white : Colors.black.withOpacity(0.2),
              //文本颜色
              color: isButtonEnable
                  ? Color(0xff44c5fe)
                  : Colors.grey.withOpacity(0.1),
              //按钮的颜色
              splashColor: isButtonEnable
                  ? Colors.white.withOpacity(0.1)
                  : Colors.transparent,
              onPressed: () {
                setState(() {
                  _buttonClickListen();
                });
              },
//                        child: Text('重新发送 (${secondSy})'),
              child: Text(
                '$buttonText',
                style: TextStyle(
                  fontSize: 13,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildOriPasswordWidget() {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(left: 10, right: 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                  crossAxisAlignment: CrossAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.baseline,
        textBaseline: TextBaseline.ideographic,
        children: <Widget>[
          Container(
            width: 60,
            child: Text(
              '原始密码',
              style: TextStyle(fontSize: 15, color: Color(0xff333333)),
            ),
          ),
          Expanded(
            child: Padding(
              padding: EdgeInsets.only(left: 20, right: 15, top: 15),
              child: TextFormField(
                maxLines: 1,
                onSaved: (value) {},
                controller: oriPasswordController,
                textAlign: TextAlign.left,
                obscureText: oriPasswordVisible,
                decoration: InputDecoration(
                  hintText: ('填写原始密码'),
                  contentPadding: EdgeInsets.only(top: -5, bottom: 0),
                  hintStyle: TextStyle(
                    color: Color(0xff999999),
                    fontSize: 15,
                  ),
                  alignLabelWithHint: true,
                  border: OutlineInputBorder(borderSide: BorderSide.none),
                  suffixIcon: IconButton(
                    icon: Icon(
                      //根据passwordVisible状态显示不同的图标
                      oriPasswordVisible
                          ? Icons.visibility_off
                          : Icons.visibility,
                      color: Theme.of(context).primaryColorDark,
                    ),
                    onPressed: () {
                      //更新状态控制密码显示或隐藏
                      setState(() {
                        oriPasswordVisible = !oriPasswordVisible;
                      });
                    },
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildNewPasswordWidget() {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(left: 10, right: 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                  crossAxisAlignment: CrossAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.baseline,
        textBaseline: TextBaseline.ideographic,
        children: <Widget>[
          Container(
            width: 60,
            child: Text(
              '新密码',
              style: TextStyle(fontSize: 15, color: Color(0xff333333)),
            ),
          ),
          Expanded(
            child: Padding(
              padding: EdgeInsets.only(left: 20, right: 15, top: 15),
              child: TextFormField(
                maxLines: 1,
                onSaved: (value) {},
                controller: newPasswordController,
                textAlign: TextAlign.left,
                obscureText: newPasswordVisible,
                decoration: InputDecoration(
                  hintText: ('填写新密码'),
                  contentPadding: EdgeInsets.only(top: -5, bottom: 0),
                  hintStyle: TextStyle(
                    color: Color(0xff999999),
                    fontSize: 15,
                  ),
                  alignLabelWithHint: true,
                  border: OutlineInputBorder(borderSide: BorderSide.none),
                  suffixIcon: IconButton(
                    icon: Icon(
                      //根据passwordVisible状态显示不同的图标
                      newPasswordVisible
                          ? Icons.visibility_off
                          : Icons.visibility,
                      color: Theme.of(context).primaryColorDark,
                    ),
                    onPressed: () {
                      //更新状态控制密码显示或隐藏
                      setState(() {
                        newPasswordVisible = !newPasswordVisible;
                      });
                    },
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildRepeatPasswordWidget() {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.only(left: 10, right: 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                  crossAxisAlignment: CrossAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.baseline,
        textBaseline: TextBaseline.ideographic,
        children: <Widget>[
          Container(
            width: 60,
            child: Text(
              '重复密码',
              style: TextStyle(fontSize: 15, color: Color(0xff333333)),
            ),
          ),
          Expanded(
            child: Padding(
              padding: EdgeInsets.only(left: 20, right: 15, top: 15),
              child: TextFormField(
                maxLines: 1,
                onSaved: (value) {},
                controller: repeatPasswordController,
                textAlign: TextAlign.left,
                obscureText: repeatPasswordVisible,
                decoration: InputDecoration(
                  hintText: ('重复密码'),
                  contentPadding: EdgeInsets.only(top: -5, bottom: 0),
                  hintStyle: TextStyle(
                    color: Color(0xff999999),
                    fontSize: 15,
                  ),
                  alignLabelWithHint: true,
                  border: OutlineInputBorder(borderSide: BorderSide.none),
                  suffixIcon: IconButton(
                    icon: Icon(
                      //根据passwordVisible状态显示不同的图标
                      repeatPasswordVisible
                          ? Icons.visibility_off
                          : Icons.visibility,
                      color: Theme.of(context).primaryColorDark,
                    ),
                    onPressed: () {
                      //更新状态控制密码显示或隐藏
                      setState(() {
                        repeatPasswordVisible = !repeatPasswordVisible;
                      });
                    },
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  bool updatePassword() {
    String newPassword = newPasswordController.text;
    String oriPassword = oriPasswordController.text;
    String verifyCode = mController.text;
    if (verifyCode == null) {
      Fluttertoast.showToast(msg: "请输入验证码！", textColor: Colors.red);
      return false;
    } else if (verifyCode != "1234") {
      Fluttertoast.showToast(msg: "验证码错误", textColor: Colors.red);
      return false;
    }
    if (checkPassword()) {
      updatePasswordAction(newPassword, oriPassword);
    } else {
      return false;
    }
  }

  bool checkPassword() {
    String newPassword = newPasswordController.text;
    String repeatPassword = repeatPasswordController.text;
    String oriPassword = oriPasswordController.text;
    if (newPassword == null) {
      Fluttertoast.showToast(msg: "请输入新密码！");
      return false;
    } else if (oriPassword == null) {
      Fluttertoast.showToast(msg: "请输入原始密码！");
      return false;
    } else if (repeatPassword == null) {
      Fluttertoast.showToast(msg: "请输入重复密码！");
      return false;
    } else if (newPassword != repeatPassword) {
      Fluttertoast.showToast(msg: "重复密码不同");
      return false;
    } else if (newPassword == oriPassword) {
      Fluttertoast.showToast(msg: "新密码和原始密码相同");
      return false;
    }
    return true;
  }

  updatePasswordAction(newPassword, oriPassword) async {
    HttpRequest.request("$BASE_URL/employee/updatePassword",
            method: "post",
            data: {
              "employeeId": InitInformation.employeeId,
              "oriPassword": AesUtil.aesEncrypt(oriPassword),
              "newPassword": AesUtil.aesEncrypt(newPassword)
            },
            token: await StorageUtil.getStringItem("token"))
        .then((value) {
      var data = json.decode(value.toString());
      if (data["code"] == 200) {
        Fluttertoast.showToast(msg: "密码修改成功,请重新登录");
        Navigator.push(
            context, MaterialPageRoute(builder: (context) => Login()));
      }
    });
  }
}
